package com.shenfa.action.systemManager;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.shenfa.bean.Organization;
import com.shenfa.dao.systemManager.organization.impl.OrganizationDaoImpl;
import com.shenfa.service.systemManager.organization.OrganizationService;

import com.shenfa.util.ResultObject;
import com.shenfa.util.sequence.SequenceUtil;

/**
 * 机构
 * @author jiangmaochun
 *
 */
public class OrganizationAction extends ActionSupport implements ModelDriven<Organization>{

	private static final long serialVersionUID = 1L;
	
	private Organization organization = new Organization();
	
	public Organization getModel() {
		return organization;
	}
	
	@Autowired
	private OrganizationService organizationService;
	@Autowired
	private SequenceUtil sequenceUtil;
	@Autowired
	private OrganizationDaoImpl organizationDaoImpl;
	
	public JSONObject result;
	
	private HttpServletRequest request;
	private static Logger log=Logger.getLogger(OrganizationAction.class);
	private int start;
	private int limit;
	private String orgNo;
	public void setStart(int start) {
		this.start = start;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public void setOrgNo(String orgNo) {
		this.orgNo = orgNo;
	}

	public OrganizationAction() {
	}
	
	/**
	 * 获取所有机构，分树形等级返回
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String fetchOrganizationResource() {
		
		List<Organization> list = organizationService.getAll();
		
		if (list == null){
			result = ResultObject.build("-1", null);
		}else{
			JSONArray jsonArray = new JSONArray();
			Map<String, JSONObject> map = new HashMap<String,JSONObject>();
			
			//把所有节点加入map集合
			for (Organization organization : list){
				JSONObject jobj = parseResource(organization);
				map.put(organization.getId(), jobj);
			}
			for (Organization organization : list){
				String key = organization.getSupperId();
				
				JSONObject jobj = map.get(organization.getId());
				if ("0".equals(key)){
				}else{
					JSONObject parent = map.get(key);
					//防止错误数据（假的父节点）
					if(null==parent){
						continue;
					}
					
					JSONArray temp = (JSONArray)parent.get("children");
					if (temp == null){
						temp = new JSONArray();
						parent.put("children", temp);
					}
					temp.add(jobj);
					map.remove(organization.getId());
				}
			}
			
			Iterator<JSONObject> ite = map.values().iterator();
			while (ite.hasNext()) {
				JSONObject jsonObject = (JSONObject) ite.next();
				jsonArray.add(jsonObject);
			}
			result = ResultObject.build("0", jsonArray);
		}
		return SUCCESS;
		
	}
	
	/**
	 * 将对象转成JSON
	 * @param res
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private JSONObject parseResource(Organization res){
		JSONObject jObj = new JSONObject();
		jObj.put("id", res.getId());
		jObj.put("name", res.getName());
		jObj.put("text", res.getName());
		jObj.put("type", res.getType());
		jObj.put("supperId", res.getSupperId());
		jObj.put("area", res.getArea());
		jObj.put("contact", res.getContact());
		jObj.put("phone", res.getPhone());
		jObj.put("postal", res.getPost());
		jObj.put("address", res.getAddress());
		return jObj;
	}
	
	/**
	 * 根据上级机构查询
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String listByParent(){
		//JSONArray ja = new JSONArray();
		request = ServletActionContext.getRequest();
		String parentId = request.getParameter("parentId");
		log.debug("start="+start+",limit="+limit+",parentId="+parentId);
		List<Organization> ja = organizationService.getListByParent(parentId, start, limit);
		result = ResultObject.build("0", ja);
		result.put("total", organizationService.queryCount(parentId));
		return SUCCESS;
	}
	
	@SuppressWarnings("unchecked")
	public String queryType(){		
		String orgType = organizationDaoImpl.queryType(orgNo);
		result = new JSONObject();
		result.put("orgType", orgType);
		return SUCCESS;
	}
	
	/**
	 * 添加机构
	 */
	public String add(){
		log.debug("address="+organization.getAddress()+",area="+organization.getArea()+",contact="+organization.getContact()+",id="+organization.getId()+",name="+organization.getName()
				+",phone="+organization.getPhone()+",post="+organization.getPost()+",state="+organization.getState()+",supperId="+organization.getSupperId()+",type="+organization.getType());
		String id=sequenceUtil.getSequence(11);
		organization.setId(id);
		organizationService.add(organization);
		return backResult(true,"机构增加成功！");
	}
	
	public Organization judgeId(String id){
		 return organizationService.getById(id);
	}
	/**
	 * 修改机构
	 */
	public String update(){
		log.debug("address="+organization.getAddress()+",area="+organization.getArea()+",contact="+organization.getContact()
				+",id="+organization.getId()+",name="+organization.getName()+",phone="+organization.getPhone()+",post="+organization.getPost()
				+",state="+organization.getState()+",supperId="+organization.getSupperId()+",type="+organization.getType());
		organizationService.update(organization);
		return backResult(true,"机构号"+organization.getId()+"修改成功");
	}
	
	/**
	 * 删除机构
	 */
	public String delete(){
		log.debug("id="+organization.getId());
		organizationService.delete(organization.getId());
		return backResult(true,"机构号"+organization.getId()+"删除成功");
	}
	
	/**
	 * 公共返回方法
	 * @param isTure
	 * @param msg
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String backResult(Boolean isTure,String msg){
		if(null==result){
			result = new JSONObject();
		}
		result.put("success", isTure);
		result.put("msg",msg);
		return SUCCESS;
	}
}
